//
// Created by Zeppyrz on 2025/11/5.
//

#include "ZeDiskClient.h"

#include <iostream>
#include <utility>

#include "DirTask.h"
#include "DownLoadTask.h"
#include "ThreadPool.h"
#include "UploadTask.h"

namespace ZeDiskGUI {

using namespace ZeDisk;

ZeDiskClient::ZeDiskClient() : server_port_(-1) {
  threadpool_ = ThreadPoolFactory::CreateThreadPool(8);
}

ZeDiskClient& ZeDiskClient::GetInstance() {
  static ZeDiskClient instance;
  return instance;
}

void ZeDiskClient::GetDir() {
  std::cout << "[INFO] Get Dir: " << root_ << " ip: " << server_ip_ << ":"
            << server_port_ << std::endl;

  auto task = std::make_shared<DirTask>();
  task->server_ip() = server_ip_;
  task->port() = server_port_;
  task->DirectoryListCallback = [this](std::string dirs) {
    std::cout << "[INFO] Server Response files: " << dirs << std::endl;
    emit DirSig(dirs);  // 激活信号，交给app渲染
  };
  threadpool_->Dispatch(task);
}

void ZeDiskClient::Upload(std::string filepath) {
  auto task = std::make_shared<UploadTask>();
  task->server_ip() = server_ip_;
  task->port() = server_port_;
  task->file_path() = std::move(filepath);
  task->upload_complete_callback_ = [this]() { emit UploadCompleteSig(); };
  threadpool_->Dispatch(task);
}

void ZeDiskClient::Download(std::string file_name, std::string local_path) {
  auto task = std::make_shared<DownLoadTask>();
  task->server_ip() = server_ip_;
  task->port() = server_port_;
  task->file_name() = file_name;
  task->local_file_path() = local_path;
  task->download_complete_callback_ = [this]() { emit DownloadCompleteSig(); };
  threadpool_->Dispatch(task);
}

}  // namespace ZeDiskGUI